home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_09_02 / 9n02100a < prev    next >
Text File  |  1990-12-15  |  2KB  |  87 lines

  1.  
  2.  
  3. #include <stdlib.h>
  4. /**
  5. *
  6. * name      sbrk -- Adjust linear heap break pointer
  7. *           rbrk -- Reset linear heap
  8. *
  9. * synopsis  b = sbrk(n);
  10. *           rbrk();
  11. *           void *b;            block address
  12. *           int n;              number of bytes
  13. *
  14. * description   This is an implementation of sbrk/rbrk
  15. *               based upon the ANSI memory allocation
  16. *               routines. Note that it uses a public
  17. *               item named _LHINCR to define the
  18. *               default size of the linear heap. This
  19. *               size is used to allocate space via
  20. *               malloc on the first call to sbrk
  21. *               unless the requested size is larger.
  22. *
  23. **/
  24. #define SBRK_ERR (void *)(-1)
  25. /**
  26. *
  27. * Linear heap parameters
  28. *
  29. **/
  30. unsigned _LHINCR = 8192;  // allocation size of
  31.                              linear heap
  32.  
  33. static char *base = 0;    // base of linear heap
  34. static unsigned size;     // size of linear heap
  35. static unsigned xbrk = 0; // current break index
  36. /**
  37. *
  38. * Allocate space from the linear heap.
  39. *
  40. **/
  41. void *sbrk(int n)
  42. {
  43. unsigned x;
  44.  
  45. if(base == 0)
  46.         {
  47.         if(n <= 0) return(SBRK_ERR);
  48.         size = (n > _LHINCR) ? n : _LHINCR;
  49.         base = malloc(size);
  50.         if(base == 0)
  51.                 {
  52.                 size = 0;
  53.                 return(SBRK_ERR);
  54.                 }
  55.         xbrk = 0;
  56.         }
  57. if(n < 0)
  58.         {
  59.         if((xbrk + n) < 0) return(SBRK_ERR);
  60.         }
  61. else
  62.         {
  63.         if((xbrk + n) > size) return(SBRK_ERR);
  64.         }
  65. x = xbrk;
  66. xbrk += n;
  67. if(n > 0) memset(&base[x],0,n);
  68. return(&base[x]);
  69. }
  70. /**
  71. *
  72. * Reset the linear heap
  73. *
  74. **/
  75. void rbrk(void)
  76. {
  77. if(base != 0) 
  78.         {
  79.         free(base);
  80.         base = 0;
  81.         size = 0;
  82.         xbrk = 0;
  83.         }
  84. }
  85.  
  86.  
  87.